package com.zhuhjay.intercept;

import com.github.benmanes.caffeine.cache.Cache;
import com.zhuhjay.model.domain.HttpResult;
import com.zhuhjay.util.ServletUtils;
import com.zhuhjay.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZhuHJay
 * @date 2023/4/26 12:29
 */
@Slf4j
public class AuthIntercept implements HandlerInterceptor {

    private final Cache<String, Object> loginUserCache;
    public AuthIntercept() {
        this.loginUserCache = SpringContextHolder.getBean("loginUserCache");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = request.getSession().getId();
        if (loginUserCache.getIfPresent(sessionId) == null) {
            ServletUtils.writeJsonResult(HttpResult.fail("登录失效, 请重新登录"));
            return false;
        }
        return true;
    }
}
